﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCompany.MyProject.Extensions.ServiceExtensions;

public static class AddSwaggerExt
{
    public static void AddSwaggerExtensions(this WebApplicationBuilder builder)
    {
        builder.Services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo()
            {
                Version = "v1",
                Title = "WebApi文档说明",
                Description = "框架说明文档 GitLab 自动部署的",
                Contact = new OpenApiContact()
                {
                    Name = "wja",
                    Email = "wja@124.com"
                }
            });

            var path = AppContext.BaseDirectory;
            var xmlPath = Path.Combine(path, "MyCompany.MyProject.WebApi.xml");
            c.IncludeXmlComments(xmlPath, true);

            var xmlModelPath = Path.Combine(path, "MyCompany.MyProject.Model.xml");
            c.IncludeXmlComments(xmlModelPath);

            // 开启小锁
            c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Description = "请输入 token ，格式为 Bearer xxxx（注意中间有空格）",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey,
                BearerFormat = "JWT",
                Scheme = "Bearer"
            });
            // 添加安全要求
            c.AddSecurityRequirement(new OpenApiSecurityRequirement()
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference()
                        {
                            Type=ReferenceType.SecurityScheme,
                            Id="Bearer"
                        }
                    },
                    new string[]{ }
                }
            });
        });
    }

    public static void UseSwagerExt(this WebApplication app)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1"));
    }
}
